package com.xsl.lession02.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.map.MapUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.xsl.lession02.pojo.FenceLocationPoint;
import com.xsl.lession02.pojo.MonitoredPerson;
import com.xsl.lession02.vo.RunParamVo;
import com.xsl.lession02.pojo.ElectronicFence;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class BaiduService {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    static {
        //驼峰转化的参数
        MAPPER.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    }

    @Autowired
    private BaiduApiService baiduApiService;

    private String BAIDU_URL = "http://yingyan.baidu.com/api/v3";


    /**
     * 创建鹰眼服务中的实体
     *
     * @param routeId 路线id
     * @return
     */
    public Boolean createEntity(String routeId) {
        String url = BAIDU_URL + "/entity/add";
        return this.baiduApiService.execute(url, Method.POST,
                this.createParam(routeId), response -> {
                    if (response.isOk()) {
                        String body = response.body();
                        JSONObject jsonObject = JSONUtil.parseObj(body);
                        return jsonObject.getInt("status") == 0;
                    }
                    return false;
                });
    }

    /**
     * 构建创建实体的参数
     *
     * @param routeId
     * @return
     */
    private Map<String, Object> createParam(String routeId) {
        return MapUtil.builder("entity_name", this.createEntityName(routeId)).build();
    }

    /**
     * 创建实体名称
     *
     * @param routeId
     * @return
     */
    private Object createEntityName(String routeId) {
        return "route_" + routeId;
    }


    /**
     * 给实体添加轨迹点
     *
     * @param routeId
     * @param runParamVo
     * @return
     */
    public Boolean uploadLocation(String routeId, RunParamVo runParamVo) {
        String url = BAIDU_URL + "/track/addpoint";
        Map<String, Object> paramMap = MapUtil.builder(new HashMap<String, Object>())
                .put("entity_name", this.createEntityName(routeId))
                .put("latitude", runParamVo.getLatitude())
                .put("longitude", runParamVo.getLongitude())
                .put("loc_time", System.currentTimeMillis() / 1000)
                .put("coord_type_input", "bd09ll")
                .put("speed", runParamVo.getSpeed()).build();

        return this.baiduApiService.execute(url, Method.POST,
                paramMap, response -> {
                    if (response.isOk()) {
                        String body = response.body();
                        JSONObject jsonObject = JSONUtil.parseObj(body);
                        return jsonObject.getInt("status") == 0;
                    }
                    return false;
                });
    }


    /**
     * 调用百度地图鹰眼服务中的接口创建电子围栏
     *
     * @param electronicFence
     * @return 百度地图电子围栏id
     */
    public Long createElectronicFence(ElectronicFence electronicFence) {
        String url = BAIDU_URL + "/fence/createpolygonfence";

        //构建多边形坐标数据
        String vertexes = CollUtil.join(electronicFence.getMutiPoints().stream()
                .map(locationPoint -> locationPoint.getLatitude() + "," + locationPoint.getLongitude())
                .collect(Collectors.toList()), ";");

        //构造提交参数
        Map<String, Object> param = MapUtil.builder(new HashMap<String, Object>())
                .put("fence_name", electronicFence.getName()) //围栏名称
                .put("vertexes", vertexes) //多边形围栏形状点， 结构：纬度,经度;纬度,经度
                .put("coord_type", "bd09ll").build();

        return this.baiduApiService.execute(url, Method.POST, param, response -> {
            if (response.isOk()) {
                String body = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if (jsonObject.getInt("status") != 0) {
                    return null;
                }

                //围栏id
                return jsonObject.getLong("fence_id");
            }
            return null;
        });
    }

    /**
     * 调用百度地图鹰眼服务中的接口创建电子围栏
     *
     * @param electronicFence
     * @return 百度地图电子围栏id
     */
    public Long addMonitoredPerson(MonitoredPerson monitoredPerson) {
        String url = BAIDU_URL + "/fence/addmonitoredperson";


        //构造提交参数
        Map<String, Object> param = MapUtil.builder(new HashMap<String, Object>())
                .put("fence_id", monitoredPerson.getFenceId())
                .put("monitored_person", monitoredPerson.getMonitoredPerson()) .build();

        return this.baiduApiService.execute(url, Method.POST, param, response -> {
            if (response.isOk()) {
                String body = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if (jsonObject.getInt("status") != 0) {
                    return null;
                }

                //围栏id
                return jsonObject.getLong("fence_id");
            }
            return null;
        });
    }

    /**
     * 调用百度地图鹰眼服务中的接口创建电子围栏
     *
     * @param fence_ids
     * @return 百度地图电子围栏id
     */
    public Long querystatusbylocation(FenceLocationPoint fenceLocationPoint) {
        String url = BAIDU_URL + "/fence/querystatusbylocation";

        //构造提交参数
        Map<String, Object> param = MapUtil.builder(new HashMap<String, Object>())
                .put("monitored_person", fenceLocationPoint.getMonitoredPerson())
                .put("fence_ids", fenceLocationPoint.getFenceIds())
                .put("longitude", fenceLocationPoint.getLongitude())
                .put("latitude", fenceLocationPoint.getLatitude())
                .put("coord_type", "bd09ll").build();

        return this.baiduApiService.execute(url, Method.GET, param, response -> {
            if (response.isOk()) {
                String body = response.body();
                JSONObject jsonObject = JSONUtil.parseObj(body);
                if (jsonObject.getInt("status") != 0) {
                    return null;
                }

                //围栏id
                return jsonObject.getLong("fence_id");
            }
            return null;
        });
    }


}
